package cn.edu.tju.elm.controller;

import cn.edu.tju.elm.model.Food;
import cn.edu.tju.elm.model.Business;
import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.elm.service.FoodService;
import cn.edu.tju.elm.service.BusinessService;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.repository.FoodRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/foods")
@Tag(name = "管理商品", description = "提供对商品的增删改查功能")
public class FoodController {
    
    private static final Logger logger = LoggerFactory.getLogger(FoodController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private FoodService foodService;
    
    @Autowired
    private FoodRepository foodRepository;

    @Autowired
    private BusinessService businessService;

    @GetMapping("/{id}")
    @Operation(summary = "获取商品详情", description = "根据ID获取商品详细信息")
    public HttpResult<Food> getFoodById(
            @Parameter(description = "商品ID", required = true) @PathVariable Long id) {
        try {
            HttpResult<Food> result = foodService.getFoodById(id);
            if (result.getSuccess()) {
                return result;
            } else {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "商品不存在");
            }
        } catch (Exception e) {
            logger.error("获取商品详情失败: {}", e.getMessage(), e);
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "获取商品详情失败: " + e.getMessage());
        }
    }

    @GetMapping("")
    @Operation(summary = "获取商品列表", description = "可以根据商家ID筛选和排序")
    public HttpResult<List<Food>> getAllFoods(
            @Parameter(description = "商家ID", example = "1") 
            @RequestParam(name = "business", required = false) Long businessId,
            @Parameter(description = "排序方式", example = "price_asc") 
            @RequestParam(name = "order", required = false) String order) {
        
        try {
            List<Food> foods;
            
            if (businessId != null) {
                // 验证商家是否存在
                HttpResult<Business> businessResult = businessService.getBusinessById(businessId);
                if (!businessResult.getSuccess() || businessResult.getData() == null) {
                    return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "商家不存在");
                }
                
                // 获取商家商品
                HttpResult<List<Food>> foodResult = foodService.getFoodsByBusinessId(businessId);
                if (!foodResult.getSuccess()) {
                    return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, foodResult.getMessage());
                }
                foods = foodResult.getData();
            } else {
                // 获取所有商品
                HttpResult<List<Food>> foodResult = foodService.getAllFoods();
                if (!foodResult.getSuccess()) {
                    return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, foodResult.getMessage());
                }
                foods = foodResult.getData();
            }
            
            // 增强排序参数处理：检查非null和非空
            if (order != null && !order.trim().isEmpty()) {
                foods = sortFoods(foods, order.trim());
            }
            
            return HttpResult.success(foods);
        } catch (Exception e) {
            logger.error("获取商品列表失败: {}", e.getMessage(), e);
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "获取商品列表失败: " + e.getMessage());
        }
    }

    @PostMapping("")
    @Operation(summary = "添加商品", description = "创建新的商品")
    public HttpResult<Food> addFood(@RequestBody Food food) {
        try {
            // 获取当前用户
            var currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 验证商家是否存在
            if (food.getBusiness() == null || food.getBusiness().getId() == null) {
                return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "必须指定商家");
            }
            
            HttpResult<Business> businessResult = businessService.getBusinessById(food.getBusiness().getId());
            if (!businessResult.getSuccess() || businessResult.getData() == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "商家不存在");
            }
            
            // 设置商品信息
            food.setCreator(currentUser.getId());
            food.setUpdater(currentUser.getId());
            
            // 添加商品
            return foodService.addFood(food);
        } catch (Exception e) {
            logger.error("添加商品失败: {}", e.getMessage(), e);
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "添加商品失败: " + e.getMessage());
        }
    }
    
    // 辅助方法：根据排序参数对商品列表进行排序
    private List<Food> sortFoods(List<Food> foods, String order) {
        if ("price_asc".equals(order)) {
            foods.sort((f1, f2) -> {
                if (f1.getFoodPrice() == null) return -1;
                if (f2.getFoodPrice() == null) return 1;
                return f1.getFoodPrice().compareTo(f2.getFoodPrice());
            });
        } else if ("price_desc".equals(order)) {
            foods.sort((f1, f2) -> {
                if (f1.getFoodPrice() == null) return 1;
                if (f2.getFoodPrice() == null) return -1;
                return f2.getFoodPrice().compareTo(f1.getFoodPrice());
            });
        } else if ("name_asc".equals(order)) {
            foods.sort((f1, f2) -> {
                if (f1.getFoodName() == null) return -1;
                if (f2.getFoodName() == null) return 1;
                return f1.getFoodName().compareTo(f2.getFoodName());
            });
        } else if ("name_desc".equals(order)) {
            foods.sort((f1, f2) -> {
                if (f1.getFoodName() == null) return 1;
                if (f2.getFoodName() == null) return -1;
                return f2.getFoodName().compareTo(f1.getFoodName());
            });
        } else {
            logger.warn("未知的排序参数: {}", order);
            // 可以抛出异常或忽略未知排序参数
            // 这里选择忽略，保持原顺序
        }
        return foods;
    }
    
    @PutMapping("/{id}")
    @Operation(summary = "全量修改商品信息", description = "仅商家可修改自己店铺的商品信息，未提供的字段将保留原值")
    public HttpResult<Food> fullUpdateFood(
            @Parameter(description = "商品ID", required = true) @PathVariable Long id,
            @RequestBody Food updatedFood) {
        try {
            // 验证用户是否登录（复用用户验证逻辑）
            var currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            Long currentUserId = currentUser.getId();

            // 验证商品是否存在（复用商品查询逻辑）
            HttpResult<Food> foodResult = foodService.getFoodById(id);
            if (!foodResult.getSuccess() || foodResult.getData() == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "商品不存在");
            }
            Food existingFood = foodResult.getData();

            // 验证权限（复用商家权限校验逻辑）
            Long businessUserId = existingFood.getBusiness().getUserId();
            if (!currentUserId.equals(businessUserId)) {
                return HttpResult.failure(ResultCodeEnum.FORBIDDEN, "没有权限修改此商品");
            }

            // 验证商家是否存在（复用商家验证逻辑）
            if (updatedFood.getBusiness() != null && updatedFood.getBusiness().getId() != null) {
                HttpResult<Business> businessResult = businessService.getBusinessById(updatedFood.getBusiness().getId());
                if (!businessResult.getSuccess() || businessResult.getData() == null) {
                    return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "商家不存在");
                }
            }

            // 确保ID一致性（防止URL与请求体ID不一致）
            updatedFood.setId(id);
            // 维护审计字段（复用更新人设置逻辑）
            updatedFood.setCreator(existingFood.getCreator()); // 保留创建人
            updatedFood.setUpdater(currentUserId); // 更新修改人

            // 字段级非空判断，仅更新非空字段
            if (updatedFood.getFoodName() != null) {
                existingFood.setFoodName(updatedFood.getFoodName());
            }
            if (updatedFood.getFoodExplain() != null) {
                existingFood.setFoodExplain(updatedFood.getFoodExplain());
            }
            if (updatedFood.getFoodImg() != null) {
                existingFood.setFoodImg(updatedFood.getFoodImg());
            }
            if (updatedFood.getFoodPrice() != null) {
                existingFood.setFoodPrice(updatedFood.getFoodPrice());
            }
            if (updatedFood.getBusiness() != null && updatedFood.getBusiness().getId() != null) {
                existingFood.setBusiness(updatedFood.getBusiness());
            }
            if (updatedFood.getRemarks() != null) {
                existingFood.setRemarks(updatedFood.getRemarks());
            }

            // 保存更新后的商品信息
            Food savedFood = foodRepository.save(existingFood);
            return HttpResult.success(savedFood);
        } catch (Exception e) {
            logger.error("修改商品失败: {}", e.getMessage(), e);
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "修改商品失败: " + e.getMessage());
        }
    }
    
    @PatchMapping("/{id}")
    @Operation(summary = "部分修改商品信息", description = "仅商家可修改自己店铺的商品信息，仅更新提供的非空字段")
    public HttpResult<Food> partialUpdateFood(
            @Parameter(description = "商品ID", required = true) @PathVariable Long id,
            @RequestBody Food updatedFood) {
        try {
            // 验证用户是否登录（复用全量更新的用户验证逻辑）
            var currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            Long currentUserId = currentUser.getId();

            // 验证商品是否存在（复用商品查询逻辑）
            HttpResult<Food> foodResult = foodService.getFoodById(id);
            if (!foodResult.getSuccess() || foodResult.getData() == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "商品不存在");
            }
            Food existingFood = foodResult.getData();

            // 验证权限（复用全量更新的权限校验逻辑，仅商品所属商家可修改）
            Long businessUserId = existingFood.getBusiness().getUserId();
            if (!currentUserId.equals(businessUserId)) {
                return HttpResult.failure(ResultCodeEnum.FORBIDDEN, "没有权限修改此商品");
            }

            // 若更新了商家信息，验证商家是否存在（复用商家验证逻辑）
            if (updatedFood.getBusiness() != null && updatedFood.getBusiness().getId() != null) {
                HttpResult<Business> businessResult = businessService.getBusinessById(updatedFood.getBusiness().getId());
                if (!businessResult.getSuccess() || businessResult.getData() == null) {
                    return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "商家不存在");
                }
            }

            // 确保ID一致性（防止URL与请求体ID不一致）
            updatedFood.setId(id);
            // 维护审计字段（复用更新人设置逻辑）
            updatedFood.setCreator(existingFood.getCreator()); // 保留创建人
            updatedFood.setUpdater(currentUserId); // 更新修改人

            // 仅更新非空字段（与全量更新逻辑一致，实现部分修改）
            if (updatedFood.getFoodName() != null) {
                existingFood.setFoodName(updatedFood.getFoodName());
            }
            if (updatedFood.getFoodExplain() != null) {
                existingFood.setFoodExplain(updatedFood.getFoodExplain());
            }
            if (updatedFood.getFoodImg() != null) {
                existingFood.setFoodImg(updatedFood.getFoodImg());
            }
            if (updatedFood.getFoodPrice() != null) {
                existingFood.setFoodPrice(updatedFood.getFoodPrice());
            }
            if (updatedFood.getBusiness() != null && updatedFood.getBusiness().getId() != null) {
                existingFood.setBusiness(updatedFood.getBusiness());
            }
            if (updatedFood.getRemarks() != null) {
                existingFood.setRemarks(updatedFood.getRemarks());
            }

            // 保存更新后的商品信息（复用仓库层保存方法）
            Food savedFood = foodRepository.save(existingFood);
            return HttpResult.success(savedFood);
        } catch (Exception e) {
            logger.error("部分修改商品失败: {}", e.getMessage(), e);
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "部分修改商品失败: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/{id}")
    @Operation(summary = "删除商品", description = "仅商家可删除自己店铺的商品")
    public HttpResult<Void> deleteFood(
            @Parameter(description = "商品ID", required = true) @PathVariable Long id) {
        try {
            // 验证用户是否登录
            var currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            Long currentUserId = currentUser.getId();

            // 验证商品是否存在
            HttpResult<Food> foodResult = foodService.getFoodById(id);
            if (!foodResult.getSuccess() || foodResult.getData() == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "商品不存在");
            }
            Food existingFood = foodResult.getData();

            // 验证权限（仅商家可删除自己的商品）
            Long businessUserId = existingFood.getBusiness().getUserId();
            if (!currentUserId.equals(businessUserId)) {
                return HttpResult.failure(ResultCodeEnum.FORBIDDEN, "没有权限删除此商品");
            }

            // 调用服务层删除方法
            return foodService.deleteFood(id);
        } catch (Exception e) {
            logger.error("删除商品失败: {}", e.getMessage(), e);
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "删除商品失败: " + e.getMessage());
        }
    }
}